import { computed, inject, onMounted, onUnmounted, Ref, ref } from 'vue'
import { useStore } from '@/store'

export type MainType = ReturnType<typeof initMain>
export type FormType = ReturnType<typeof initData>

// 获取grid参数，el传入获取dom元素字符串
export function getGridData (el: string) {
  const load = ref(false)
  // 计算合并单元格样式
  const gridArea = computed(() => (val: string) => {
    const [row, column] = val.split('*').map(Number)
    if (!row && !column) return ''
    return {
      gridColumnStart: `span ${column}`,
      gridRowStart: `span ${row}`
    }
  })

  // 基础参数
  const client = ref({
    scale: 4, // 比例
    gap: 10, // 间距
    w: 0,
    h: 0
  })

  // 动态设置gird-item宽高
  const setItemClient = () => {
    setTimeout(() => {
      const dom = document.querySelector(el)
      const rect = dom?.getBoundingClientRect() as DOMRect
      const scale = 4
      const gap = (scale - 1) * client.value.gap / scale
      client.value.w = rect.width / scale - gap
      // 减去底部10px,用于显示滚动条
      client.value.h = (rect.height - client.value.gap) / scale - gap
    }, 80)
  }
  onMounted(() => {
    setItemClient()
    window.addEventListener('resize', setItemClient)
    setTimeout(() => {
      load.value = true
    }, 20)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', setItemClient)
    stop()
  })
  return {
    load,
    client,
    gridArea,
    setItemClient
  }
}
// 生成唯一ID
export function generateId () {
  return Math.floor(Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000)
}

// JSON初始数据
export function initMain () {
  return {
    id: generateId(),
    name: '',
    component: '',
    norms: [] as string[],
    normsVal: '',
    active: false,
    img: ''
  }
}
// 表单初始数据
export function initData (store: ReturnType<typeof useStore>) {
  const mainList = []
  for (let i = 0; i < 16; i++) {
    mainList.push(initMain())
  }
  return {
    id: 0,
    name: '',
    status: 0,
    createdBy: store.state.user.name,
    mainList
  }
}

// 获取表单provide
export function getFormData () {
  return inject('formData') as Ref<FormType>
}

// file文件转化为base64
function changeFileToBaseURL (file: File) {
  return new Promise<string>((resolve) => {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file)
    fileReader.onload = function () {
      resolve(this.result as string)
    }
  })
}

// base64转换为二进制文件流
function dataURLtoFile (dataurl: string, filename: string) {
  const arr = dataurl.split(',')
  const mime = (arr[0].match(/:(.*?);/) as string[])[1]

  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }

  return new File([u8arr], filename, { type: mime })
}

// 压缩图片
export async function pressImg (param: {
  file: File // 文件二进制流
  width: number // 输出图片宽度
  height: number // 输出图片高度
  name?: string // 输出图片名称, 不传使用原图片名称
}) {
  const fileName = param.name || param.file.name
  const fileType = param.file.type
  const base64 = await changeFileToBaseURL(param.file)
  return new Promise((resolve) => {
    if (base64) {
      const image = new Image()
      image.src = base64
      image.onload = function () {
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')

        canvas.width = param.width
        canvas.height = param.height
        // 把图片绘制到canvas上面
        context && context.drawImage(image, 0, 0, canvas.width, canvas.height)
        // 压缩图片，获取到新的base64Url
        const newImageData = canvas.toDataURL(fileType, 1)
        // 将base64转化成文件流
        const resultFile = dataURLtoFile(newImageData, fileName)
        resolve(resultFile)
      }
    }
  })
}
